<?php

class Admin_video_Controller extends Base_Controller {

    public $restful = true;
    public $_data = array();

    public function get_index() {

        $per_page = Input::get('per_page', 20);
        $videoLogic = new VideoLogic();
        $ret = $videoLogic->getVideolist($per_page);
        unset($videoLogic);
        return View::make('admin.video.list')->with("video_list", $ret);
    }

    public function post_del() {
        $id = Input::get('id');
        $videoLogic = new VideoLogic();
        $this->_data["state"] = $videoLogic->deleteVideo($id);
        if ($this->_data["state"] == 1)
            $this->_data["state"] = true;
        else
            $this->_data["state"] = false;
        echo Response::json(array("state" => $this->_data['state']));
    }

    public function post_manage() {
        $id = Input::get('id');
        $this->_data["input"] = Input::get();
        $this->_data["state"] = False;
        $videoLogic = new VideoLogic();
        //$this->_data["vp"] = $this->validate_parameter();
        $update_array = array();
        $db_array = array('title', 'category_id', 'description', 'duration', 'price', 'tag', 'image', 'ctime', 'type', 'viewed', 'sort_order', 'status');
        foreach ($db_array as $key) {
            $value = Input::get($key);
            if (!empty($value))
                $update_array[$key] = $value;
            else {
                $update_array[$key] = "";
            }
        }
        if (file_exists(path("public") . $update_array['image'])) {
            $image = $update_array['image'];
            $new_image = str_replace("upload_tmp", "upload", $image);
            File::move(path("public") . $update_array['image'], path("public") . $new_image);
            $update_array['image'] = $new_image;
        }
        $update_array['status'] = "1";

        if (!empty($id)) {
            //更新新闻
            //if($this->_data["vp"] === True ){
            $this->_data["state"] = $videoLogic->updateVideCommInfo($id, $update_array['title'], $update_array['category_id'], $update_array['duration'], $update_array['image'], $update_array['price'], $update_array['type'], $update_array['sort_order'], $update_array['status']);
            //var_dump($this->_data["state"]);
            if ($this->_data['state'] == false) {
                return Redirect::to("admin/video/manage?id=$id");
            }
            $this->_data["state"] = $videoLogic->updateVideoDesc($id, $update_array['description'], $update_array['tag']);
            //var_dump($this->_data["state"]);
            if ($this->_data['state'] == false) {
                return Redirect::to("admin/video/manage?id=$id");
            }
            //}
        } else {
            //增加新闻
            //if($this->_data["vp"] === True ){
            $this->_data["state"] = $videoLogic->addVideoInfo($update_array['title'], $update_array['description'], $update_array['category_id'], $update_array['duration'], $update_array['image'], $update_array['price'], $update_array['type'], $update_array['sort_order'], $update_array['status'], $update_array['tag']);
            if ($this->_data["state"] == 1)
                $this->_data["state"] = true;
            else
                $this->_data["state"] = false;
            //var_dump($this->_data["state"]);
            //if($this->_data['state'] == false ) {return Redirect::to("admin/video/manage?id=$id");}
            //}
        }
        return Redirect::to("admin/video/index");
    }

    public function get_manage() {
        /*
          CREATE TABLE IF NOT EXISTS `video` (
          `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
          `title` varchar(255) NOT NULL,
          `category_id` int(11) unsigned NOT NULL DEFAULT '0',
          `duration` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'unit:min',
          `image` varchar(255) NOT NULL COMMENT '''''',
          `price` int(11) unsigned NOT NULL DEFAULT '0',
          `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '0/1 视频/直播',
          `viewed` int(11) unsigned NOT NULL DEFAULT '0',
          `sort_order` int(11) unsigned NOT NULL DEFAULT '0',
          `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0/1 无效/有效',
          `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          `mtime` int(11) unsigned NOT NULL DEFAULT '0',



          CREATE TABLE IF NOT EXISTS `video_description` (
          `id` int(11) unsigned NOT NULL,
          `title` varchar(255) NOT NULL,
          `description` text NOT NULL,
          `tag` varchar(512) DEFAULT NULL,
          `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          `mtime` int(11) unsigned NOT NULL DEFAULT '0',
          PRIMARY KEY (`id`)
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8 PACK_KEYS=0;

         */
        $db_array = array('title', 'category_id', 'description', 'duration', 'price', 'tag', 'image', 'ctime', 'type', 'viewed', 'sort_order', 'status');

        $video = array();
        $top_cat = array();
        foreach ($db_array as $value) {
            $video[$value] = '';
        }
        $id = Input::get('id');
        $video['id'] = $id;
        $videoLogic = new VideoLogic();
        $this->_data["video"] = $videoLogic->getVideoInfoByID($id);
		$brothers = array();
        if (!empty($this->_data["video"])) {
            foreach ($db_array as $value) {
                $video[$value] = $this->_data["video"]->$value;
            }
        $this->_categoryModel = new CategoryLogic();
			$crumb = $this->_categoryModel->getHieraCats($video['category_id']);
			if($crumb){
				foreach($crumb as $key => $value){
					$brothers[$value['id']] =$this->_categoryModel->getBrolevelCats($value['id']);
				}
			}
        }else{

        $categoryLogic = new CategoryLogic();
        $top_cat = $categoryLogic->getNextLevelCats(0);
        unset($categoryLogic);
		}

        return View::make('admin.video.manage')->with('video', $video)->with('top_cat', $top_cat)->with("brothers",$brothers);
    }

    //list item
    public function action_retrieve() {
        if (!Input::has('videoID')) {
            return Response::json(array(
                        'errno' => UMSErrcode::PARA_ERR,
            ));
        }
        $videoID = intval(Input::get('videoID'));
        $videoLogic = new VideoLogic();
        $ret = $videoLogic->getVideoInfoByID($videoID);
        unset($videoLogic);
        if (false === $ret) {
            return Response::json(array());
        }
        return Response::json($ret);
    }

    public function action_add() {
        if (!Input::has('videoID') || !Input::has('title') || !Input::has('desc') || !Input::has('cid') ||
                !Input::has('duration') || !Input::has('image') || !Input::has('price') || !Input::has('type') ||
                !Input::has('so') || !Input::has('status')) {
            return Response::json(array(
                        'errno' => UMSErrcode::PARA_ERR,
            ));
        }
        $videoID = intval(Input::get('videoID'));
        $title = Input::get('title');
        $desc = Input::get('desc');
        $cid = Input::get('cid');
        $duration = Input::get('duration');
        $image = Input::get('image');
        $price = intval(Input::get('price'));
        $type = intval(Input::get('type'));
        $sort_order = intval(Input::get('so'));
        $status = intval(Input::get('status'));
        $videoLogic = new VideoLogic();
        $ret = $videoLogic->addVideoInfo($title, $desc, $cid, $duration, $image, $price, $type, $sort_order, $status);
        unset($videoLogic);
        if ($ret) {
            Response::json(
                    array(
                        'errno' => UMSErrcode::SUCCESS,
            ));
        } else {
            Response::json(
                    array(
                        'errno' => UMSErrcode::SYS_ERR,
            ));
        }
    }

    //更新普通信息
    public function action_updateinfo() {
        if (!Input::has('videoID') || !Input::has('title') || !Input::has('cid') || !Input::has('duration') ||
                !Input::has('image') || !Input::has('price') || !Input::has('type') || !Input::has('so') ||
                !Input::has('status')) {
            return Response::json(array(
                        'errno' => UMSErrcode::PARA_ERR,
            ));
        }
        $videoID = intval(Input::get('videoID'));
        $title = Input::get('title');
        $cid = Input::get('cid');
        $duration = Input::get('duration');
        $image = Input::get('image');
        $price = intval(Input::get('price'));
        $type = intval(Input::get('type'));
        $sort_order = intval(Input::get('so'));
        $status = intval(Input::get('status'));

        $videoLogic = new VideoLogic();
        $ret = $videoLogic->updateVideCommInfo($videoID, $title, $cid, $duration, $image, $price, $type, $sort_order, $status);
        unset($videoLogic);
        if ($ret) {
            Response::json(
                    array(
                        'errno' => UMSErrcode::SUCCESS,
            ));
        } else {
            Response::json(
                    array(
                        'errno' => UMSErrcode::SYS_ERR,
            ));
        }
    }

    //更新视频描述
    public function action_updatedesc() {
        if (!Input::has('videoID') || !Input::has('desc')) {
            return Response::json(array(
                        'errno' => UMSErrcode::PARA_ERR,
            ));
        }
        $videoID = intval(Input::get('videoID'));
        $desc = Input::get('desc');
        $tag = '';
        if (Input::has('tag')) {
            $tag = Input::get('tag');
        }
        $videoLogic = new VideoLogic();
        $ret = $videoLogic->updateVideoDesc($videoID, $desc, $tag);
        if ($ret) {
            Response::json(array(
                'errno' => UMSErrcode::SUCCESS,
            ));
        } else {
            Response::json(array(
                'errno' => UMSErrcode::SYS_ERR,
            ));
        }
    }

    public function post_upload() {

        if ($_FILES["uploadFile"]["error"] > 0) {
            echo Response::json(array("error" => $_FILES["uploadFile"]["error"], "err_msg" => "上传失败"));
        } else {
            if (file_exists("upload/" . $_FILES["uploadFile"]["name"])) {
                //echo $_FILES["uploadFile"]["name"] . " already exists. ";
                //echo Response::json(array("error"=>$_FILES["uploadFile"]["error"],);
            } else {
                $pic_name = base64_encode(time()) . "." . strtolower(File::extension($_FILES["uploadFile"]["name"]));
                move_uploaded_file($_FILES["uploadFile"]["tmp_name"], path("public") . "upload_tmp/" . $pic_name);
                list($width, $height, $type, $attr) = getimagesize(path("public") . "upload_tmp/" . $pic_name);
                echo Response::json(array('savepath' => '/upload_tmp', 'savename' => $pic_name, 'width' => $width, 'height' => $height));
            }
        }
    }

    function resizeImg($imgName, $maxWidth, $maxHeight, $saveName = '') {//图片生成缩略图
        $arrImg = explode(".", $imgName);
        if ($arrImg[1] == "jpg") {
            $im = imagecreatefromjpeg($imgName);
        } elseif ($arrImg[1] == "png") {
            $im = imagecreatefrompng($imgName);
        } elseif ($arrImg[1] == "gif") {
            $im = imagecreatefromgif($imgName);
        }
        $imgNewName = empty($saveName) ? $imgName : $saveName;
        if ($im) {
            $width = imagesx($im);
            $height = imagesy($im);
            if (($maxWidth && $width >= $maxWidth) || ($maxHeight && $height >= $maxHeight)) {
                if ($maxWidth && $width >= $maxWidth) {
                    $widthRadio = $maxWidth / $width;
                    $resizeWidth = true;
                }
                if ($maxHeight && $height >= $maxHeight) {
                    $heightRadio = $maxHeight / $height;
                    $resizeHeight = true;
                }
                if ($resizeHeight && $resizeWidth) {
                    if ($widthRadio > $heightRadio) {
                        $radio = $heightRadio;
                    } else {
                        $radio = $widthRadio;
                    }
                } elseif ($resizeHeight) {
                    $radio = $heightRadio;
                } elseif ($resizeWidth) {
                    $radio = $widthRadio;
                }

                $newwidth = $radio * $width;
                $newheight = $radio * $height;

                if (file_exists($imgNewName))
                    unlink($imgNewName);

                if (function_exists("imagecopyresampled")) {

                    $newim = imagecreatetruecolor($newwidth, $newheight);
                    imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                } else {

                    $newim = imagecreate($newwidth, $newheight);
                    imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                }
                imagejpeg($newim, $imgNewName);
                imagedestroy($newim);
            } else {
                $arr = getimagesize($imgName);
                $this->imgEndWidth = $arr[0];
                $this->imgEndHeight = $arr[1];
                imagejpeg($im, $imgNewName);
            }
        }
        return $imgNewName;
    }

    public function post_thumb() {
        $orig = Input::get('orig');
        $maxWidth = Input::get('width');
        $maxHeight = Input::get('height');
        //function resizeImg($imgName,$maxWidth,$maxHeight,$saveName='');
        $imgName = path("public") . $orig;
        $newName = base64_encode(time()) . "." . strtolower(File::extension($orig));
        $saveName = path("public") . "/upload_tmp/" . $newName;
        $this->resizeImg($imgName, $maxWidth, $maxHeight, $saveName);
        echo Response::json(array('newName' => '/upload_tmp/' . $newName, 'width' => $maxWidth, 'height' => $maxHeight));
    }

}

?>
